package com.baijiayun.live.ui.toolbox.timer;

import android.annotation.SuppressLint;
import android.content.Context;
import android.media.SoundPool;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;

import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.CheckedTextView;
import android.widget.EditText;
import android.widget.TextView;

import com.baijiayun.live.ui.R;
import com.baijiayun.live.ui.base.BaseDialogFragment;
import com.baijiayun.live.ui.utils.QueryPlus;
import com.baijiayun.liveuibase.utils.BaseUIUtils;
import com.baijiayun.liveuibase.utils.DisplayUtils;
import com.baijiayun.liveuibase.utils.ThemeDataUtil;

/**
 * 计时器
 */
public class TimerFragment extends BaseDialogFragment implements TimerContract.View {
    private TimerContract.Presenter presenter;
    private QueryPlus $;
    private Context context;
    private boolean isPublish;
    private EditText etMin;
    private EditText etSecond;
    private CheckedTextView tvPublish;
    private CheckedTextView tvCountDown;
    private CheckedTextView tvCountUp;
    private boolean canEditable = true;
    private long duration;
    private SoundPool soundPool;
    private int rootViewVisibleHeight;
    private boolean upStatus = false;

    @Override
    public void setPresenter(TimerContract.Presenter presenter) {
        setBasePresenter(presenter);
        this.presenter = presenter;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        this.context = context;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setCancelable(false);
    }

    @SuppressLint("SetTextI18n")
    @Override
    protected void init(Bundle savedInstanceState ,Bundle arguments) {
        $ = QueryPlus.with(contentView);
        hideBackground();
        tvPublish = (CheckedTextView) $.id(R.id.tv_publish).view();
        etMin = (EditText) $.id(R.id.dialog_timer_et_min).view();
        etMin.setTextColor(ThemeDataUtil.getColorEnableMainText2Warning(context));
        etSecond = (EditText) $.id(R.id.dialog_timer_et_second).view();
        etSecond.setTextColor(ThemeDataUtil.getColorEnableMainText2Warning(context));
        tvCountDown = (CheckedTextView) $.id(R.id.dialog_timer_tv_count_down).view();
//        tvCountDown.setTextColor(ThemeDataUtil.getColorCheckWhite2MainText(context));
        tvCountUp = (CheckedTextView) $.id(R.id.dialog_timer_tv_count_up).view();
//        tvCountUp.setTextColor(ThemeDataUtil.getColorCheckWhite2MainText(context));
        etMin.setOnFocusChangeListener((focusChangeListener));
        etSecond.setOnFocusChangeListener(focusChangeListener);
        etMin.setOnEditorActionListener(editorActionListener);
        etSecond.setOnEditorActionListener(editorActionListener);

        $.id(R.id.tv_publish).clicked(v -> {
            if (!isPublish) {
                //启动
                publish(getTimerSeconds());
            } else {
                //暂停
                pause();
            }
            setTabClickable(canEditable);
        }).textColor(ThemeDataUtil.getColorCheckWhite2MainText(context));

        if (presenter.isTimerShowy()){
            $.id(R.id.dialog_end).visible();
        } else {
            $.id(R.id.dialog_end).gone();
        }

        $.id(R.id.dialog_end).clicked(v -> {
            presenter.requestTimerEnd();
            reset();
            $.id(R.id.dialog_end).gone();
        });
        $.id(R.id.dialog_timer_exit).clicked(v -> {
            dismiss();
        });
        tvCountDown.setOnClickListener(v -> {
            tvCountUp.setChecked(false);
            tvCountDown.setChecked(true);
        });
        tvCountUp.setOnClickListener(v -> {
            tvCountUp.setChecked(true);
            tvCountDown.setChecked(false);
        });
    }

    private void reset() {
        setTimer(0);
        setButtonState(TimerPresenter.start_timer);
    }

    private boolean isCountDown() {
        CheckedTextView textView = (CheckedTextView) $.id(R.id.dialog_timer_tv_count_down).view();
        return textView.isChecked();
    }

    private void setTabClickable(boolean clickable) {
        $.id(R.id.dialog_timer_tv_count_down).view().setEnabled(clickable);
        $.id(R.id.dialog_timer_tv_count_up).view().setEnabled(clickable);
    }

    private void publish(long duration) {
        if (!isLegal()) {
            showToast(getString(R.string.timer_error_tip,isCountDown()?getString(R.string.timer_countdown):getString(R.string.timer_countup)));
            return;
        }
        if (getString(R.string.timer_start).equals(tvPublish.getText().toString())) {
            this.duration = duration;
        }

        presenter.requestTimerStart(0,this.duration,isCountDown());

        onDestroyView();
    }

    private void pause() {
        setButtonState(TimerPresenter.continue_timer);
        presenter.requestTimerPause(0, duration, isCountDown());
    }

    private boolean isLegal() {
        return getTimerSeconds() > 0;
    }

    private long getTimerSeconds() {
        long min = 0, second = 0;
        long seconds = 0;
        try {
            min = Long.parseLong(etMin.getText().toString());
            min = min > 59 ? 59 : min;
            second = Long.parseLong(etSecond.getText().toString());
            second = second > 59 ? 59 : second;
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        seconds = min * 60 + second;
        return seconds;
    }

    public static void showInput(Context context, View view) {
        InputMethodManager inputMethodManager = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        inputMethodManager.showSoftInputFromInputMethod(view.getWindowToken(), 0);
    }
    @Override
    public void setTimer(long remainSeconds) {
        long min = remainSeconds / 60;
        long second = remainSeconds % 60;
        etMin.setText(String.valueOf(min >= 10 ? min : ("0" + min)));
        etSecond.setText(String.valueOf(second >= 10 ? second : ("0" + second)));
    }

    private void showEditable(boolean canEditable) {
        etMin.setEnabled(canEditable);
        etSecond.setEnabled(canEditable);
        tvCountDown.setEnabled(canEditable);
        tvCountUp.setEnabled(canEditable);
    }

    @Override
    public void showViewState(boolean isCountDown) {
        tvCountDown.setChecked(isCountDown);
        tvCountUp.setChecked(!isCountDown);
    }

    @Override
    public void hideButton() {
        $.id(R.id.dialog_close).visibility(View.GONE);
        $.id(R.id.ll_tab).visibility(View.GONE);
        $.id(R.id.tv_publish).visibility(View.GONE);
        showEditable(false);
    }

    @Override
    public void showTimerEnd() {
        if(soundPool != null) {
            soundPool.release();
        }
        soundPool = BaseUIUtils.playAudio(getContext(), R.raw.timer_end);
        reset();
    }

    @Override
    public void showTimerPause(boolean isPause) {
        $.id(R.id.dialog_base_title).text(getString(isPause ? R.string.timer_pause_tip : R.string.timer));
    }

    @Override
    public void setButtonState(String state) {
        if (TextUtils.isEmpty(state)){
            return;
        }

        switch (state) {
            case TimerPresenter.pause_timer:
                isPublish = true;
                canEditable = false;
                showTimerPause(false);
                tvPublish.setText(getString(R.string.live_timer_pause_count));
                $.id(R.id.dialog_end).visible();
                break;
            case TimerPresenter.continue_timer:
                isPublish = false;
                canEditable = false;
                showTimerPause(true);
                tvPublish.setText(getString(R.string.timer_start));
                $.id(R.id.dialog_end).visible();
                break;
            case TimerPresenter.start_timer:
                isPublish = false;
                canEditable = true;
                showTimerPause(false);
                tvPublish.setText(getString(R.string.timer_start));
                break;
            default:
                break;
        }
        showEditable(canEditable);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if(soundPool != null) {
            soundPool.release();
        }
    }

    @Override
    public int getLayoutId() {
        return R.layout.bjy_fragment_timer;
    }

    @Override
    protected void setWindowParams(WindowManager.LayoutParams windowParams) {
        getDialog().getWindow().setBackgroundDrawable(ContextCompat.getDrawable(getContext(), R.drawable.shape_window_common_bg));
        windowParams.width = (int) getResources().getDimension(R.dimen.live_timer_window_width);
        windowParams.height = (int) getResources().getDimension(R.dimen.live_timer_window_height);
        windowParams.gravity = Gravity.CENTER;
    }

    @Override
    protected boolean hasWindowAnim() {
        return false;
    }

    private View.OnFocusChangeListener focusChangeListener = (v, hasFocus) -> {
        if (v instanceof  EditText){
            EditText et = (EditText)v;
            if (!hasFocus){
                int value = et.getText().length() > 0 ? Integer.parseInt(et.getText().toString()) : 0;
                if (value > 59){
                    value = 59;
                }
                String tmp = String.valueOf(value);
                while (tmp.length() < 2){
                    tmp = "0".concat(tmp);
                }
                et.setText(tmp);
            }else {
                et.setSelection(et.getText().length());
            }
            if (v.getId() == R.id.dialog_timer_et_min && !hasFocus){
                etSecond.requestFocus();
                showInput(context, etSecond);
            }
        }
    };

    TextView.OnEditorActionListener editorActionListener = (v, actionId, event) -> {
        v.clearFocus();
        return false;
    };
}
